<!--通过负责部门获取机构树组件-->
<template>
  <div>
    <div class="search-form">
      <el-form :inline="true" >
        <el-form-item label="负责部门" class="txt-bold" >
          <el-select v-model="deptId" placeholder="请选择负责部门"   @change="switchDepartment" :clearable="false">
            <el-option v-for="(item,index) in fzbmData" :key="index" :label="item.deptName"
                       :value="item.deptId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <el-input
      placeholder="输入机构名称进行过滤"
      v-model="searchForm.name" class="mb10" @blur="searchHandle" clearable>
    </el-input>
    <el-table
      v-loading="treeLoading"
      :data="treeTableFilter"
      border
      ref="tableRef"
      :row-class-name="rowClass"
      header-align="center"
      :header-cell-style="{ background: '#f2f2f2', color: '#000' }"
      :height="tableHeight"
      @selection-change="handleSelectionChange"
      @select="selectRow"
      @select-all="selectAllRow"
      row-key="id"
      key="first"
      :tree-props="{
                children: 'children',
                hasChildren: 'hasChildren',
              }"
      highlight-current-row
      @row-click="rowClick"
      default-expand-all
    >
      <el-table-column
        type="selection"
        align="center"
        header-align="center"
        width="55"
        v-if="select">
      </el-table-column>
      <el-table-column prop="name" show-overflow-tooltip label="机构名称" align="left" min-width="140">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
          <span class="nav" v-if="arrow">
                    <i class="el-icon-caret-right"> </i>
                  </span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {getOrgOfDept} from "@/api/bonus/calculateorgconfig";
import {getJiangJinBm} from "@/api/admin/dept";
let proVal = null
export default {
  name: "orgTreeByBm",
  props:{
    height:{ //树表格的高等于 100vh - height
      type:Number,
      default:250
    },
    select:{
      type:Boolean,
      default:false
    },
    arrow:{
      type:Boolean,
      default:true
    }
  },
  watch:{
    searchForm:{
      handler(newV,oldV){
        this.filterTreeData() ;
      },
      deep:true,
      immediate:true
    },
    height:{
      handler(newV,oldV){
        this.tableHeight = 'calc(100vh'+ ' - '+ this.height + 'px)' ;
      },
      immediate:true,
      deep:true
    }
  },
  data(){
    return{
      treeLoading:false,
      searchForm: {name: '',},
      deptId:'',
      fzbmData:{} ,
      treeTableFilter:[],
      expandRow: [],
      multipleSelection:[]
      //height:'calc(100vh - 250px)'
    }
  },

  computed: {

  },
  created(){
    //this.getJiangJinJg() ;
  },
  methods:{
    //获取奖金管理人机构
    getJiangJinJg(data) {
      this.parentTableData = data || [];
      this.treeLoading = true ;
      getJiangJinBm().then(res => {
        if (res.data.data != null && res.data.data.length > 0) {
          this.deptId = res.data.data[0].deptId;
          this.deptName = res.data.data[0].deptName;
          this.fzbmData = res.data.data;
          this.getOrgTree() ;
        } else {
          this.$notify.error("没有相关负责部门")
        }
        //this.treeLoading = false ;
      }).catch(err =>{
       // this.treeLoading = false ;
      });
    },
    switchDepartment(val){
      this.getOrgTree() ;
      //this.$forceUpdate() ;
    },
    getOrgTree(){
      if (!this.deptId) return ;
      this.treeLoading = true ;
      getOrgOfDept({pid:this.deptId}).then(res=>{
        if (res.data.code == 0){
          this.tableData = res.data.data
          this.treeTableFilter = this.filterTreeData() ; //前端实现搜索功能
          //勾选回显
          this.$nextTick(()=>{
            this.selectedRows() ;
          })

        }else{
          this.$message.error('同步失败')
        }
        this.treeLoading = false ;
      }).catch(err=>{
        this.treeLoading = false ;
      })
    },
    filterTreeData(){
        let treeData = this.tableData
        //获取需要刷选的属性
        const propList = this.exitProps(this.searchForm)
        //初始化
        proVal = {}
        //赋属性
        propList.forEach(item => {
          proVal[item] = ''
        })
        //如果都为false 则不进行过滤，直接获取所有
        if (propList.length > 0) {
          let handleTreeData = this.handleTreeData(treeData, this.searchForm, Object.keys(this.searchForm))
          this.setExpandRow(handleTreeData)
          this.expandRow = this.expandRow.join(',').split(',')
          return handleTreeData
        }
        return this.tableData
    },
    selectedRows(){
      this.selectedIds = this.parentTableData.map(item => {
        return item.bonusDeptId
      })
      this.treeTableFilter.map((item) => {
        if (this.selectedIds.includes(item.bonusDeptId)){
          this.$refs.tableRef.toggleRowSelection(item,true)
        }
        if (item.children) {
          this.setChildren(item.children);
        }
      });
    },
    // 父节点含多个子层级
    setChildren(children) {
      children.map((item) => {
        if (this.selectedIds.includes(item.bonusDeptId)){
          this.$refs.tableRef.toggleRowSelection(item,true)
        }
        if (item.children) {
          this.setChildren(item.children);
        }
      });
    },
    searchHandle(){
      this.getOrgTree() ;
    },
    rowClass(){
      return "rowNavigation" ;
    },
    rowClick(item){
      this.currentDept = item ; //当前点击的机构
      this.$emit('sendCurrentOrg',Object.assign(item,{fzbmId:this.deptId}))
    },
    /**
     * 根据搜索条是否有值，把需要搜索的属性给保存返回
     */
    exitProps (obj) {
      let propList = []
      for (const prop in obj) {
        if (obj[prop]) {
          propList.push(prop)
        }
      }
      return propList
    },
    /**
     * 处理筛选出来的数据
     * @param treeData
     */
    setExpandRow (treeData) {
      if (treeData.length) {
        for (let i of treeData) {
          this.expandRow.push(i.id)
          if (i.children.length) {
            this.setExpandRow(i.children)
          }
        }
      }
    },
    /**
     * 过滤筛选数据
     * @param treeData 树形数据
     * @param searchForm 查询条件
     * @param searchNames 查询条件的字段 用来与树形对象匹配
     * @returns {*[]}
     */
    handleTreeData (treeData, searchForm, searchNames) {
      if (!treeData || treeData.length === 0) {
        return []
      }
      //获取需要进行筛选的属性
      const propList = this.exitProps(this.searchForm)
      const array = []
      //把搜索条件的值进行提取赋值
      propList.forEach(prop => {
        proVal[prop] = searchForm[prop]
      })
      treeData.forEach(item => {
        let match = false
        //搜索条件的值是否和数据相匹配
        let isEqual=true
        propList.forEach(prop => {
          isEqual = isEqual && item[prop].includes(proVal[prop])
        })
        match |= isEqual
        if (this.handleTreeData(item.children, searchForm, searchNames).length > 0 || match) {
          array.push({
            ...item,
            children: this.handleTreeData(item.children, searchForm, searchNames),
          })
        }
      })
      return array
    },
    handleSelectionChange(list){
      this.multipleSelection = list
      this.$emit('selectOrg',list)
    },
    // 勾选父节点时，子层级一起勾选或一起取消勾选
    selectRow(selection, row) {
      let data = selection.some((item) => {
        return row.id === item.id;
      });
      if (data) {
        // 勾选节点时
        if (row.children) {
          this.setChildrenMulSel(row.children, true);
        }
      } else {
        // 取消勾选节点时
        if (row.children) {
          this.setChildrenMulSel(row.children, false);
        }
      }
    },
    // 全选按钮
    selectAllRow(selection) {
      // 全选
      let isSelect = selection.some((item) => {
        let tableDataIds = this.treeTableFilter.map((data) => data.id);
        if (tableDataIds.indexOf(item.id) !== -1) {
          return true;
        } else {
          return false;
        }
      });
      // 全不选
      let isCancel = !this.treeTableFilter.every((item) => {
        let selectIds = selection.map((data) => data.id);
        if (selectIds.indexOf(item.id) !== -1) {
          return true;
        } else {
          return false;
        }
      });
      if (isSelect) {
        selection.map((item) => {
          if (item.children) {
            this.setChildrenMulSel(item.children, true);
          }
        });
      }
      if (isCancel) {
        this.treeTableFilter.map((item) => {
          if (item.children) {
            this.setChildrenMulSel(item.children, false);
          }
        });
      }
    },
    // 父节点含多个子层级
    setChildrenMulSel(children, type) {
      children.map((item) => {
        this.toggleSelection(item, type);
        if (item.children) {
          this.setChildrenMulSel(item.children, type);
        }
      });
    },

    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.tableRef.toggleRowSelection(row, select);
        });
      }
    },

  }
}
</script>

<style scoped>

</style>
